// Package middleware 中间件包
package middleware

import (
	"math"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"go.uber.org/zap"
)

// Log 日志中间件
func Log() gin.HandlerFunc {
	return func(c *gin.Context) {
		handleID := uuid.New().String()
		zap.L().Info("request",
			zap.String("handle id", handleID),
			zap.Any("url", c.Request.URL),
			zap.Any("req", c.Request.Body))
		//开始计时
		startTime := time.Now()
		//调用后续的处理函数
		c.Next()
		//处理函数运行完后停止运行并计算运行时间
		stopTime := time.Since(startTime)
		spendTime := int64(math.Ceil(float64(stopTime.Nanoseconds()) / 1000000.0))
		//查找主机名
		hostName, _ := os.Hostname()

		//获取请求方法和路径
		method := c.Request.Method
		resp, _ := c.Get("resp")
		err, ok := c.Get("error")
		if ok {
			zap.L().Info("gin log",
				zap.String("handle id", handleID),
				zap.String("path", c.FullPath()),
				zap.Int64("spendTime", spendTime),
				zap.String("host", hostName),
				zap.String("method", method),
				zap.String("ip:", c.ClientIP()),
				zap.Int("status", c.Writer.Status()),
				zap.Any("resp", resp),
				zap.Error(err.(error)),
			)
			return
		}
		zap.L().Info("gin log",
			zap.String("handle id", handleID),
			zap.String("path", c.FullPath()),
			zap.Int64("spendTime", spendTime),
			zap.String("host", hostName),
			zap.String("method", method),
			zap.String("ip:", c.ClientIP()),
			zap.Int("status", c.Writer.Status()),
			zap.Any("resp", resp),
		)
	}
}
